package com.learn.security.web.controller;


import com.fasterxml.jackson.annotation.JsonView;
import com.learn.security.dto.User;
import com.learn.security.exception.UserNotExistException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



@Api(value = "用户管理的控制器")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 注册用户
     */
    @ApiOperation(value = "分页获取所有用户")
    @PostMapping("/register")
    public void register(User user, HttpServletRequest request){

        // 注册逻辑
        String userId = user.getUserName();

        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));

    }

    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails user) {
        return user;
    }


    /**
     * 查询所有user
     * 1.@PageableDefault 定义缺省的分页对象
     * @param pageable 分页对象
     */
    @ApiOperation(value = "分页获取所有用户")
    @GetMapping()
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@PageableDefault(sort = "id,asc") Pageable pageable){
        List<User> list = new ArrayList<>();
        list.add(new User(1,"三儿","顾慎为","123",new Date()));
        list.add(new User(2,"四儿","李青萍","123",null));
        list.add(new User(3,"胖儿","路明妃","123",new Date()));
        return list;
    }

    /**
     * 查询单个user
     * 1.使用@PathVariable映射url片段到java方法的参数
     * 2.在url声明中使用正则表达式
     * 3.使用@JsonView控制输出内容
     */
    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@ApiParam(value = "用户id") @PathVariable Integer id){
        if(id.equals(0)){
            throw new UserNotExistException(id);
        }
        User user = new User(3,"胖儿","路明妃","123",new Date());
        return user;
    }

    /**
     * 创建User对象
     * 1.@RequestBody 作用来接受并装在对象
     * 2.@Valid 配合实体中的验证信息（如@NotNull）来验证信息格式是否正确，验证不同过不会进入方法体，并将错误装入BindingResult对象
     * @param user 提交的user
     * @param errors BindingResult对象，作用：如果Valid不通过，仍然可以进入方法体
     * @return user对象
     */
    @PostMapping
    public User create(@Valid @RequestBody User user, BindingResult errors){

        // 来记录错误信息
        if(errors.hasErrors()){
           errors.getAllErrors().stream()
                   .forEach(x -> System.out.println(((FieldError)x).getField()+ x.getDefaultMessage()));
        }
        System.out.println(user);
        user.setId(3);
        return user;
    }

    /**
     * 修改user(BindingResult在@Valid 不通过时使用，用来查询原因，一般不用)
     *
     */
    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user){
        System.out.println(user);
        user.setId(3);
        return user;
    }

    /**
     * 删除user
     */
    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable String id) {
        System.out.println(id);
    }
}
